﻿using Arc.DairyMan.DairyMan.BusinessLogic;
using Arc.DairyMan.DairyMan.Common;
using Arc.DairyMan.DairyMan.Model;
using Arc.WinForms.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Arc.DairyMan.DairyMan.UI
{
    public partial class frmPayment : ArcForm
    {
        #region Variables & Properties
        DataSet _DS = new DataSet();
        DataSet _DSSearch = new DataSet();
        SabhasadTransactions Model;
        blSabhasadTransactions BL;
        int _SabhasadId = 0;
        blSabhasad _blSabhasad;
        blSabhasadTransactions _blSabhasadTransactions;
        #endregion

        public frmPayment()
        {
            InitializeComponent();

            BL = new blSabhasadTransactions();
            Model = (SabhasadTransactions)BL.ModelObj;
            BL.DS = _DS;

            _blSabhasad = new blSabhasad();
            _blSabhasad.DS = _DSSearch;

            _blSabhasadTransactions = new blSabhasadTransactions();
            _blSabhasadTransactions.DS = _DSSearch;

            ResetForm();
        }

        private void txtCode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCode.Text))
                return;
            _blSabhasad.Search("Code = '" + txtCode.Text + "'");
            if (_DSSearch.Tables.Contains("Sabhasad") && _DSSearch.Tables["Sabhasad"].Rows.Count > 0)
            {
                txtName.Text = _DSSearch.Tables["Sabhasad"].Rows[0]["Name"].ToString();
                _SabhasadId = Convert.ToInt32(_DSSearch.Tables["Sabhasad"].Rows[0]["SabhasadId"]);
            }

            ShowPendingAmount();
        }

        private void ShowPendingAmount()
        {
            _blSabhasadTransactions.Select("SabhasadId = " + _SabhasadId);
            if (_DSSearch.Tables.Contains("SabhasadTransactions") && _DSSearch.Tables["SabhasadTransactions"].Rows.Count > 0)
            {
                DataTable _dtDetails = _DSSearch.Tables["SabhasadTransactions"];

                decimal _MilkCollectionAmount = _dtDetails.AsEnumerable().Where(r => Convert.ToInt32(r["TransactionType"]) == 1).Sum(r => Convert.ToDecimal(r["Amount"]));
                decimal _PaidAmount = _dtDetails.AsEnumerable().Where(r => Convert.ToInt32(r["TransactionType"]) == 2).Sum(r => Convert.ToDecimal(r["Amount"]));

                decimal _UnpaidAmount = _MilkCollectionAmount - _PaidAmount;
                txtPending.Text = _UnpaidAmount.ToString();

                _dtDetails.Columns.Add("Type", typeof(string), "iif(TransactionType = 1,'Milk Collection','Payment')");

                DataTable _dtFiltered = _dtDetails.DefaultView.ToTable(false, "Date", "Type", "Amount");

                grdDetails.DataSource = _dtFiltered;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateForm();
                Model.SabhasadId = _SabhasadId;
                Model.TransactionType = 2; // Payment
                Model.Date = DateTime.Now;
                Model.Amount = Convert.ToDecimal(txtPayment.Text);

                BL.Transaction(true);

                ResetForm();
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void ValidateForm()
        {
            if (_SabhasadId == 0)
            {
                txtCode.Focus();
                throw new Exception("Please select an existing Sabhasad Code.");
            }
            else if (string.IsNullOrEmpty(txtPayment.Text))
            {
                txtPayment.Focus();
                throw new Exception("Please enter Payment Amount.");
            }
        }

        void ResetForm()
        {
            foreach (Control ctl in this.Controls.GetControls<ArcTextBox>())
                ctl.Text = string.Empty;

            Model.SetDefaultValues();
            _SabhasadId = 0;
            grdDetails.DataSource = null;
            grdDetails.Clear();
            grdDetails.Rows.Count = 1;
            txtCode.Focus();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        private void frmPayment_Load(object sender, EventArgs e)
        {
            ResetForm();
        }

        bool payHasDot = false;
        private void txtPayment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
            {
                // Allow Digits and BackSpace char 
            }
            else if (e.KeyChar == '.' && !payHasDot)
            {
                //Allows only one Dot Char 
                payHasDot = true;
            }
            else { e.Handled = true; }
        }

        private void btnSelectSabhasad_Click(object sender, EventArgs e)
        {
            frmSearch_Eng _frmSearch = new frmSearch_Eng();
            _frmSearch.Hidden_Field.AddRange(new[] { "SabhasadId" });
            _frmSearch.BusinessClass = _blSabhasad;
            _frmSearch.EditButton.Text = "Select";
            _frmSearch.ShowDialog();
            if (_frmSearch.PressedButton == Press_Button.Edit)
            {
                DataRow _dr = _DSSearch.Tables["Sabhasad"].Rows[0];

                _SabhasadId = Convert.ToInt32(_dr["SabhasadId"]);
                txtCode.Text = _dr["Code"].ToString();
                txtName.Text = _dr["Name"].ToString();
            }
        }
    }
}
